"""
二手交易平台API主应用
"""
import logging
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session
from sqlalchemy import text
from typing import List

from config import settings
from database import get_db, engine, Base
from auth import get_current_active_user, AuthHandler
from models import User
from schemas import BaseResponse, UserResponse, ChangePasswordRequest

# 导入路由模块
from routers import auth, users, products, trades, messages, reviews, wallet

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title="二手交易平台API",
    description="基于FastAPI的二手交易平台后端API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

@app.middleware("http")
async def log_requests(request, call_next):
    logger.debug(f"Received request: {request.method} {request.url}")
    print(f"Received request: {request.method} {request.url}")
    try:
        response = await call_next(request)
        logger.debug(f"Response status: {response.status_code}")
        print(f"Response status: {response.status_code}")
        return response
    except Exception as e:
        logger.error(f"Error processing request: {e}")
        print(f"Error processing request: {e}")
        raise

@app.on_event("startup")
async def startup_event():
    """应用启动时自动创建数据库表"""
    try:
        # 创建所有表
        Base.metadata.create_all(bind=engine)
        print("数据库表创建成功")
    except Exception as e:
        print(f"数据库表创建失败: {e}")

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件目录
# app.mount("/static", StaticFiles(directory="static"), name="static")

# 注册路由
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(users.router, prefix="/api/users", tags=["用户管理"])
app.include_router(wallet.router, prefix="/api/wallet", tags=["钱包管理"])
app.include_router(products.router, prefix="/api/products", tags=["商品管理"])
app.include_router(trades.router, prefix="/api/trades", tags=["交易管理"])
app.include_router(messages.router, prefix="/api/messages", tags=["消息系统"])
app.include_router(reviews.router, prefix="/api/reviews", tags=["评价系统"])

@app.get("/", response_model=BaseResponse)
async def root():
    """根路径，返回API基本信息"""
    return BaseResponse(
        message=f"二手交易平台API v1.0.0 - 欢迎使用"
    )

@app.get("/health", response_model=BaseResponse)
async def health_check(db: Session = Depends(get_db)):
    """健康检查接口"""
    logger.debug("Health check request received")
    try:
        # 测试数据库连接
        db.execute(text("SELECT 1"))
        logger.debug("Database connection successful")
        return BaseResponse(message="服务运行正常")
    except Exception as e:
        logger.error(f"健康检查数据库错误: {e}")
        print(f"健康检查数据库错误: {e}")
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"数据库连接异常: {str(e)}"
        )

@app.get("/me", response_model=UserResponse)
async def get_current_user_info(
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户信息"""
    return current_user


@app.put("/me/password", response_model=BaseResponse)
async def change_password(
    change_password_data: ChangePasswordRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """修改用户密码"""
    # 验证当前密码是否正确
    if not AuthHandler.verify_password(change_password_data.current_password, current_user.password_hash):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前密码错误"
        )
    
    # 检查新密码是否与原密码相同
    if change_password_data.current_password == change_password_data.new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="新密码不能与当前密码相同"
        )
    
    # 更新密码
    current_user.password_hash = AuthHandler.get_password_hash(change_password_data.new_password)
    db.commit()
    
    return BaseResponse(message="密码修改成功")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level="info"
    )